import React, { useEffect, useState } from "react";
import cls from "@/styles/pages/users/CreateUser.module.scss";
import { UserI } from "@/models/user";
import { CreateUserAvatar } from "@/feature/CreateUser/CreateUserAvatar/CreateUserAvatar";
import CreateUserForm from "@/feature/CreateUser/CreateUserForm/CreateUserForm";
import { getUser, patchUser } from "@/api/users";
import { useNavigate, useParams } from "react-router-dom";

const EditUser = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [user, setUser] = useState<Partial<UserI>>();
  const updateUser = (v: Partial<UserI>) => {
    setUser((p) => ({ ...p, ...v }));
  };

  useEffect(() => {
    if (id) getUser(id).then((res) => setUser(res));
  }, [id]);

  const onSave = () => {
    patchUser(user).then(() => navigate("/users"));
  };

  return (
    <div className={cls.root}>
      <div className={cls.block}>
        {!!user && <CreateUserAvatar user={user} updateUser={updateUser} />}
      </div>
      <div className={cls.block}>
        {!!user && (
          <CreateUserForm
            user={user}
            updateUser={updateUser}
            onSave={() => onSave()}
            isEdit
          />
        )}
      </div>
    </div>
  );
};

export default EditUser;
